package com.thb.pay.mchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thb.pay.core.constant.PayConstant;
import com.thb.pay.db.service.impl.BaseServiceImpl;
import com.thb.pay.db.utils.QueryUtils;
import com.thb.pay.mchant.entity.MchNotify;
import com.thb.pay.mchant.mapper.MchNotifyMapper;
import com.thb.pay.mchant.service.MchNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 商户-通知表 服务实现类
 * </p>
 *
 * @author lucky
 * @since 2019-07-21
 */
@Service
public class MchNotifyServiceImpl extends BaseServiceImpl<MchNotifyMapper, MchNotify> implements MchNotifyService {

    @Autowired
    private MchNotifyMapper mchNotifyMapper;

    @Override
    public MchNotify findByOrderId(String orderId) {
        LambdaQueryWrapper<MchNotify> wrapper = QueryUtils.buildLambdaQuery(MchNotify.class);
        wrapper.eq(MchNotify::getOrderId, orderId);
        return this.selectOne(wrapper);
    }

    @Override
    public int updateMchNotifySuccess(String orderId, String result, int notifyCount) {
        MchNotify mchNotify = new MchNotify();
        mchNotify.setStatus(PayConstant.MCH_NOTIFY_STATUS_SUCCESS);
        mchNotify.setResult(result);
        mchNotify.setNotifyCount(notifyCount);
        mchNotify.setLastNotifyTime(new Date());

        List values = new LinkedList<>();
        values.add(PayConstant.MCH_NOTIFY_STATUS_NOTIFYING);
        values.add(PayConstant.MCH_NOTIFY_STATUS_FAIL);

        LambdaQueryWrapper<MchNotify> wrapper = QueryUtils.buildLambdaQuery(MchNotify.class);
        wrapper.eq(MchNotify::getOrderId, orderId);
        wrapper.in(MchNotify::getStatus, values);
        return mchNotifyMapper.update(mchNotify, wrapper);
    }

    @Override
    public int updateMchNotifyFail(String orderId, String result, int notifyCount) {
        MchNotify mchNotify = new MchNotify();
        mchNotify.setStatus(PayConstant.MCH_NOTIFY_STATUS_FAIL);
        if(result != null && result.length() > 2000) {
            mchNotify.setResult(result.substring(0, 2000));
        }else {
            mchNotify.setResult(result);
        }
        mchNotify.setNotifyCount(notifyCount);
        mchNotify.setLastNotifyTime(new Date());

        List values = new LinkedList<>();
        values.add(PayConstant.MCH_NOTIFY_STATUS_NOTIFYING);

        LambdaQueryWrapper<MchNotify> wrapper = QueryUtils.buildLambdaQuery(MchNotify.class);
        wrapper.eq(MchNotify::getOrderId, orderId);
        wrapper.in(MchNotify::getStatus, values);
        return mchNotifyMapper.update(mchNotify, wrapper);
    }
}
